﻿using System.Windows.Interactivity;
using Microsoft.Phone.Controls;
using System.Windows;
using System.Windows.Input;
using System.ComponentModel;

namespace WP7Contrib.View.Controls.Behaviors
{
    /// <summary>
    /// This behaviour, when associated with a Panorama control, will reduce the opacity
    /// of each PanoramaItem while the user slides the control.
    /// </summary>
    public class PanoramaOpacityBehaviour : Behavior<Panorama>
    {
        #region DPs

        /// <summary>
        /// Gets or sets the opacity used for the panorama items whilst the user is 'sliding'
        /// </summary>
        [Description("Indicates the opacity used for the panorama items whilst the user is 'sliding'")]
        [Category("Appearance")]
        public double Opacity
        {
            get { return (double)GetValue(OpacityProperty); }
            set { SetValue(OpacityProperty, value); }
        }

        /// <summary>
        /// Identifies the Opacity dependency property
        /// </summary>
        public static readonly DependencyProperty OpacityProperty =
            DependencyProperty.Register("Opacity", typeof(double),
            typeof(PanoramaOpacityBehaviour), new PropertyMetadata(0.7));

        #endregion


        #region overrides

        protected override void OnAttached()
        {
            base.OnAttached();
           
            AssociatedObject.ManipulationDelta += Panorama_ManipulationDelta;
            AssociatedObject.ManipulationCompleted += Panorama_ManipulationCompleted;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();

            AssociatedObject.ManipulationDelta -= Panorama_ManipulationDelta;
            AssociatedObject.ManipulationCompleted -= Panorama_ManipulationCompleted;
        }

        #endregion

        #region private

        private void Panorama_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {            
            foreach (FrameworkElement fe in AssociatedObject.Items)
            {
                // restore the previous opacity
                fe.Opacity = 1.0;
            }
        }

        private void Panorama_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            foreach (FrameworkElement fe in AssociatedObject.Items)
            {
                // store the opacity and set the new value
                fe.Opacity = Opacity;
            }
        }

        #endregion

    }
}
